<template>
  <a-card :bordered="false">
    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="48">
          <a-col :md="8" :sm="24">
            <a-form-item label="登录账号">
              <a-input v-model="queryParam.loginName" placeholder=""/>
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <a-form-item label="手机号码">
              <a-input v-model="queryParam.userPhone" placeholder=""/>
            </a-form-item>
          </a-col>
          <template v-if="advanced">
            <a-col :md="8" :sm="24">
              <a-form-item label="用户姓名">
                <a-input v-model="queryParam.userName" placeholder=""/>
              </a-form-item>
            </a-col>
          </template>
          <a-col :md="!advanced && 8 || 24" :sm="24">
            <span class="table-page-search-submitButtons" :style="advanced && { float: 'right', overflow: 'hidden' } || {} ">
              <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
              <a-button style="margin-left: 8px" @click="() => queryParam = {}">重置</a-button>
              <a @click="toggleAdvanced" style="margin-left: 8px">
                {{ advanced ? '收起' : '展开' }}
                <a-icon :type="advanced ? 'up' : 'down'"/>
              </a>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <div class="table-operator">
      <a-button type="primary" icon="plus" @click="$refs.addUser.add()">新建</a-button>
      <a-button type="dashed" @click="tableOption">{{ optionAlertShow && '关闭' || '开启' }}提示</a-button>
      <a-dropdown v-action:edit v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="remove">
            <remove-user ref="removeUser" :userIds="selectedRowKeys.join(',')" @ok="handleOk"/>
          </a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px">
          批量操作 <a-icon type="down" />
        </a-button>
      </a-dropdown>
    </div>

    <s-table
      ref="table"
      size="default"
      rowKey="key"
      :columns="columns"
      :data="loadData"
      :alert="options.alert"
      :rowSelection="options.rowSelection"
      showPagination="auto"
    >
      <span slot="action" slot-scope="text, record">
        <template>
          <a @click="handleEdit(record)">编辑</a>
          <a-divider type="vertical" />
          <a @click="handleResetPwd(record)">密码</a>
          <a-divider type="vertical" />
          <remove-user ref="removeUser" :userIds="String(record.userId)" @ok="handleOk"/>
        </template>
      </span>
    </s-table>
    <add-user ref="addUser" :roles="roles" @ok="handleOk" />
    <edit-user ref="editUser" :roles="roles" @ok="handleOk"/>
    <reset-pwd-user ref="resetPwdUser" @ok="handleOk"/>
  </a-card>
</template>

<script>
import moment from 'moment'
import { STable } from '@/components'
import { queryUser } from '@/api/basic/user'
import AddUser from './modules/user/AddUser'
import EditUser from './modules/user/EditUser'
import RemoveUser from './modules/user/RemoveUser'
import ResetPwdUser from './modules/user/ResetPwdUser'

// 用于处理过滤器动态获取数据
let that

const userSexMap = {
  1: {
    color: 'cyan',
    text: '男'
  },
  2: {
    color: 'red',
    text: '女'
  }
}

const userTypeMap = {
  1: {
    status: 'error',
    text: '超管'
  },
  2: {
    status: 'success',
    text: '用户'
  }
}

export default {
  name: 'UserList',
  components: {
    STable,
    AddUser,
    EditUser,
    RemoveUser,
    ResetPwdUser
  },
  data () {
    return {
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {},
      // 角色对象
      roles: [],
      // 表头
      columns: [
        {
          title: '登录账号',
          dataIndex: 'loginName',
          align: 'center'
        },
        {
          title: '姓名',
          dataIndex: 'userName',
          align: 'center'
        },
        {
          title: '手机号码',
          dataIndex: 'userPhone',
          align: 'center',
          sorter: true
        },
        {
          title: '新建时间',
          dataIndex: 'gmtCreate',
          align: 'center',
          customRender: (text) => moment(text).format('YYYY-MM-DD')
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: '150px',
          align: 'center',
          scopedSlots: { customRender: 'action' }
        }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        // 统一处理查询参数，便于后端表格DTO用固定参数接收
        const queryJson = { 'queryParam': JSON.stringify(this.queryParam) }
        return queryUser(Object.assign(parameter, queryJson))
          .then(res => {
            return res.result
          })
      },
      selectedRowKeys: [],
      selectedRows: [],

      // custom table alert & rowSelection
      options: {
        alert: { show: true, clear: () => { this.selectedRowKeys = [] } },
        rowSelection: {
          selectedRowKeys: this.selectedRowKeys,
          onChange: this.onSelectChange
        }
      },
      optionAlertShow: false
    }
  },
  filters: {
    userSexTextFilter (type) {
      return userSexMap[type].text
    },
    userSexColorFilter (type) {
      return userSexMap[type].color
    },
    userTypeTextFilter (type) {
      return userTypeMap[type].text
    },
    userTypeStatusFilter (type) {
      return userTypeMap[type].status
    },
    roleTextFilter (roleId) {
      let roleName = ''
      for (const role of that.roles) {
        if (parseInt(role.id) === parseInt(roleId)) {
          roleName = role.name
          break
        }
      }
      return roleName
    }
  },
  beforeCreate () {
    that = this
  },
  created () {
    this.tableOption()
  },
  methods: {
    tableOption () {
      if (!this.optionAlertShow) {
        this.options = {
          alert: { show: true, clear: () => { this.selectedRowKeys = [] } },
          rowSelection: {
            selectedRowKeys: this.selectedRowKeys,
            onChange: this.onSelectChange
          }
        }
        this.optionAlertShow = true
      } else {
        this.options = {
          alert: false,
          rowSelection: null
        }
        this.optionAlertShow = false
      }
    },
    handleEdit (record) {
      this.$refs.editUser.edit(record)
    },
    handleResetPwd (record) {
      this.$refs.resetPwdUser.resetPwd(record.userId)
    },
    handleOk () {
      this.$refs.table.clearSelected()
      this.$refs.table.refresh(false)
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    toggleAdvanced () {
      this.advanced = !this.advanced
    }
  }
}
</script>
